package top.sdaily.business.service.crm.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.sdaily.business.mapper.crm.OrganizationMapper;
import top.sdaily.business.model.crm.Organization;
import top.sdaily.business.service.crm.OrganizationService;
import top.sdaily.core.mybatis.Conditions;
import top.sdaily.core.mybatis.Page;
import top.sdaily.core.utils.IdGeneratorUtils;
import top.sdaily.web.exception.FailedException;

import java.util.Date;
import java.util.List;

/**
 * Created by TsujiShiki on 2017/02/09.
 */
@Service
@Transactional
public class OrganizationServiceImpl implements OrganizationService {

    @Autowired
    OrganizationMapper organizationMapper;

    @Override
    public List<Organization> getAllOrganization() {
        return organizationMapper.findList(new Conditions(Organization.class).addOrderBy("createdate").sortDesc());
    }

    @Override
    public List<Organization> getPageOrganization(Page<Organization> page, String customerId) {
        List<Organization> pageResult = null;
        if (customerId != null && !"".equals(customerId) && !"undefined".equals(customerId)) {
            pageResult = organizationMapper.findList(new Conditions(Organization.class).eq("customer_id", customerId).addOrderBy("createdate").sortDesc().page(page));
        } else {
            pageResult = organizationMapper.findList(new Conditions(Organization.class).addOrderBy("createdate").sortDesc().page(page));
        }
        return pageResult;
    }

    @Override
    public Organization getOrganizationById(String id) {
        return organizationMapper.findOne(new Conditions(Organization.class).id(id));
    }

    @Override
    public int insertOrganization(Organization organization) {
        Organization tmpOrganization = organizationMapper.findOne(new Conditions(Organization.class).eq("org_code", organization.getOrgCode()));
        if(tmpOrganization != null) {
            throw new FailedException("组织编号已存在");
        }
        organization.setPkid(IdGeneratorUtils.fresh());
        return organizationMapper.insert(organization);
    }

    @Override
    public int updateOrganization(Organization organization) {
        organization.setUpdatedate(new Date());
        return organizationMapper.update(organization);
    }

}
